package com.ynet.middleground.user.model;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ifp.util.core.JsonUtil;
import com.ynet.core.exception.BusinessException;
import com.ynet.host.HostConstants;
import com.ynet.host.client.HostSenderService;
import com.ynet.host.http.HttpRequest;
import com.ynet.host.http.HttpResponse;
import com.ynet.middleground.user.bean.CustomerInformationReq;
import com.ynet.middleground.user.bean.MasterDataSymbol;
import com.ynet.middleground.user.bean.SupplierInformationReq;
import com.ynet.middleground.user.common.SystemConstant;
import com.ynet.middleground.user.dao.EnterpriseBasicInfoMapper;
import com.ynet.middleground.user.dto.*;
import com.ynet.middleground.user.entity.EnterpriseBasicInfo;
import com.ynet.middleground.user.external.master.MasterDataSystemConfig;
import com.ynet.middleground.user.utils.ApiUtil;
import com.ynet.middleground.user.utils.CommUtils;
import com.ynet.middleground.user.utils.Map2BeanUtil;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: 2019-10-12_userCenter
 * @description:
 * @author: DaiGaoLe
 * @create: 2019-11-10 17:33
 **/
@Component
public class MasterDataSystemModel extends ServiceImpl<EnterpriseBasicInfoMapper, EnterpriseBasicInfo> {

    @Autowired
    private HostSenderService hostSenderService;

    @Autowired
    private Mapper dozerBeanMapper;

    @Autowired
    private ApiUtil apiUtil;

    @Autowired
    private Mapper mapper;


    @Autowired
    MasterDataSystemConfig masterDataSystemConfig;

    public List<CustomerInformationDto> getMasterDataCustomer(CustomerInformationReq requestObject) throws Exception {
        List<CustomerInformationDto> customerInformationDtos = new ArrayList<>();
        String url = masterDataSystemConfig.getApiHost() + masterDataSystemConfig.getUrlCustomer();
//        Map<String, Object> bodyTemp = (Map<String, Object>) Map2BeanUtil.objectToMap(requestObject);
        Map map = JSONObject.parseObject(JSONObject.toJSONString(requestObject), Map.class);
        Map<String, Object> body = new HashMap<>();
//        Map<String, Object> columns = new HashMap<>();
        map.remove("operationUserId");
        map.remove("requestTime");
        map.remove("traceId");
        map.remove("channel");
        map.remove("pagerInfo");
        map.remove("class");
//        bodyTemp.forEach((key, value) -> {
//            if (value != null) {
//                columns.put(key, value);
//            }
//        });
        if(requestObject.getPagerInfo().getPageNum()!=0&&requestObject.getPagerInfo().getPageSize()!=0){
            body.put("offset",(requestObject.getPagerInfo().getPageNum()-1)*requestObject.getPagerInfo().getPageSize());
            body.put("limit",requestObject.getPagerInfo().getPageSize());
        }
        body.put("userKey", masterDataSystemConfig.getKey());
        body.put("tableName", "m_customer_information");
        body.put("columns",map);
        JSONObject apiResult = apiUtil.sendApi(null,body,url,HostConstants.HTTP_METHOD_POST,"获取主数据系统客户信息");
        JSONArray dataList = apiResult.getJSONArray("dataList");
        customerInformationDtos = dataList.toJavaList(CustomerInformationDto.class);
        requestObject.getPagerInfo().setTotal(apiResult.getInteger("dataCount"));
//        customerInformationDto = mapper.map(apiResult.getJSONArray("dataList"),CustomerInformationDto.class);
        //masterDataSystemDto = commGetFactorVerificationDto(null, body, url, HostConstants.HTTP_METHOD_POST,SystemConstant.MASTER_DATA_SYSTEM_TYPE_CUSTOMER);
        return customerInformationDtos;
    }

//    private CustomerInformationDto commGetFactorVerificationDto(Map<String, String> headMap,
//                                                                   Map<String, Object> body, String url, String httpMethod, String type) {
//        // 声明变量 begin
//        HttpRequest request = new HttpRequest();
//        // 声明变量 end
//        // 请求Url
//        request.setUrl(url);
//        // 暂只支持POST和GET，如果不设定，就使用yml中配置的默认值
//        request.setMethod(httpMethod);
//        // 通过url传递的参数，POST和GET均可
//        if (headMap == null) {
//            headMap = new HashMap<>();
//        }
//        request.setHeader(headMap);
//        Map<String, String> paramsString = new HashMap<>();
//        for (String k : body.keySet()) {
//            paramsString.put(k, String.valueOf(body.get(k)));
//        }
//        request.setParams(paramsString);
//        // 暂只支持POST和GET，如果不设定，就使用yml中配置的默认值
//        request.setMethod(httpMethod);
//        request.setMessage(body);
//        JSONObject resultCfcaJsonObj = null;
//        try {
//            HttpResponse response = (HttpResponse) hostSenderService.request("id_http", request, JSONObject.class);
//            // 这是响应的头信息
//            // 这是响应的http状态码，只有合法的状态才会返回，其它状态码会抛异常
//            // 200为默认的合法状态码，如有需求，可在yml中可自定义其它状态码
//            System.out.println(response.getStatus());
//            // 这是响应的报文体反格式化之后的对象
//            resultCfcaJsonObj = (JSONObject) response.getMessage();
//        } catch (Exception e) {
            // TODO 异常处理
//            throw new BusinessException(e.getMessage());
//        }
//        Map<String, Object> resultCfcaMap = JsonUtil.parseJSON2Map(resultCfcaJsonObj);
//        List<Map> data = (List) resultCfcaMap.get("customerInformation");
//        CustomerInformationDto temp = new CustomerInformationDto();
//        if (SystemConstant.MASTER_DATA_SYSTEM_TYPE_CUSTOMER.equals(type)) {// 查询客户信息
//            temp.setCustomerInformationDtos(new ArrayList<CustomerInformationDto>());
//        } else if (SystemConstant.MASTER_DATA_SYSTEM_TYPE_SUPPLIER.equals(type)) {// 供应商信息查询供应商信息查询
//            temp.setSupplierInformationDtos(new ArrayList<SupplierInformationDto>());
//        }
//
//        for (Map obj : data) {
//            CustomerInformationDto customerInformationDto = null;
//            SupplierInformationDto supplierInformationDto = null;
//            try {
//                if (temp.getCustomerInformationDtos() != null ) {// 查询客户信息
//                    customerInformationDto = (CustomerInformationDto) CommUtils.mapToObject(obj, CustomerInformationDto.class);
//                }
//                if (temp.getSupplierInformationDtos() != null ) {// 供应商信息查询供应商信息查询
//                    supplierInformationDto = (SupplierInformationDto) CommUtils.mapToObject(obj, SupplierInformationDto.class);
//                }
//                List<Map> linkmanBlockList = (List<Map>) obj.get("linkmanBlock");
//                if (linkmanBlockList != null) {
//                    for (Map linkmanBlockObj : linkmanBlockList) {
//                        LinkmanBlockDto linkmanBlock = null;
//                        List<LinkmanBlockDto> list1 = new ArrayList<>();
//                        try {
//                            linkmanBlock = (LinkmanBlockDto) CommUtils.mapToObject(linkmanBlockObj,
//                                    LinkmanBlockDto.class);
//                            list1.add(linkmanBlock);
//
//                            if (customerInformationDto != null) {// 查询客户信息
//                                customerInformationDto.setLinkmanBlockDtos(list1);
//                            }
//                            if (supplierInformationDto != null) {// 供应商信息查询供应商信息查询
//                                supplierInformationDto.setLinkmanBlockDtos(list1);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            throw new BusinessException(e.getMessage());
//                        }
//                    }
//
//                }
//                List<Map> datachangeLogBlockList = (List<Map>) obj.get("datachangeLogBlock");
//                if (datachangeLogBlockList != null) {
//                    for (Map datachangeLogBlockObj : datachangeLogBlockList
//                    ) {
//                        DataChangeLogBlockDto dataChangeLogBlock = null;
//                        List<DataChangeLogBlockDto> list2 = new ArrayList<>();
//                        try {
//                            dataChangeLogBlock = (DataChangeLogBlockDto) CommUtils.mapToObject(datachangeLogBlockObj,
//                                    DataChangeLogBlockDto.class);
//                            list2.add(dataChangeLogBlock);
//                            if (customerInformationDto != null){
//                                customerInformationDto.setDataChangeLogBlockDtos(list2);
//                            }
//                            if (supplierInformationDto != null) {
//                                supplierInformationDto.setDataChangeLogBlockDtos(list2);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            throw new BusinessException(e.getMessage());
//                        }
//                    }
//                }
//                List<Map> bankBlockList = (List<Map>) obj.get("bankBlock");
//                if (bankBlockList != null) {
//                    for (Map bankBlockObj : bankBlockList) {
//                        DataSystemBankBlockDto bankBlock = null;
//                        List<DataSystemBankBlockDto> list3 = new ArrayList<>();
//                        try {
//                            bankBlock = (DataSystemBankBlockDto) CommUtils.mapToObject(bankBlockObj,
//                                    DataSystemBankBlockDto.class);
//                            list3.add(bankBlock);
//                            if (customerInformationDto != null) {
//                                customerInformationDto.setDataSystemBankBlockDtos(list3);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            throw new BusinessException(e.getMessage());
//                        }
//                    }
//                }
//
//                if (temp.getCustomerInformationDtos() != null) {
//                    temp.getCustomerInformationDtos().add(customerInformationDto);
//                }
//                if (temp.getSupplierInformationDtos() != null) {
//                    temp.getSupplierInformationDtos().add(supplierInformationDto);
//                }
//                temp = customerInformationDto;
//            } catch (Exception e) {
//                e.printStackTrace();
//                throw new BusinessException(e.getMessage());
//            }
//        }
//
//        return temp;
//    }

    @Transactional(rollbackFor = Exception.class)
    public void getCustomerId() {
        String url = masterDataSystemConfig.getApiHost() + masterDataSystemConfig.getUrlCustomer();
        Map<String, Object> body = new HashMap<>();
        Map<String, String> headMap = new HashMap<>();
        body.put("userKey", masterDataSystemConfig.getKey());
        body.put("tableName", "m_customer_information");

//        body.put("columns",map);
        //2020-07-22修改，从ur_user_base_information表中迁移master_data_system_id和kingdee_id字段到ur_enterprise_basic_info
        QueryWrapper<EnterpriseBasicInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("master_data_system_id");
        CustomerInformationReq requestObject = new CustomerInformationReq();
        List<EnterpriseBasicInfo> enterpriseBasicInfos = this.baseMapper.selectList(queryWrapper);
        enterpriseBasicInfos.forEach(obj -> {
            MasterDataSymbol masterDataSymbol = new MasterDataSymbol();
            masterDataSymbol.setValue(obj.getCompanyName());
            masterDataSymbol.setSymbol("=");
            requestObject.setCustomer_name(masterDataSymbol);
            Map map = JSONObject.parseObject(JSONObject.toJSONString(requestObject), Map.class);
            map.remove("operationUserId");
            map.remove("requestTime");
            map.remove("traceId");
            map.remove("channel");
            map.remove("pagerInfo");
            map.remove("class");
            body.put("columns",map);
            //            body.put("columns","customer_name":{"value":"香驰粮油+'","symbol":"="}');
            JSONObject apiResult = apiUtil.sendApi(null, body, url, HostConstants.HTTP_METHOD_POST, "获取主数据系统客户信息");
            JSONArray dataList = apiResult.getJSONArray("dataList");
            List<CustomerInformationDto> customerInformationDtos = dataList.toJavaList(CustomerInformationDto.class);
            if(customerInformationDtos.size()>0) {
                obj.setMasterDataSystemId(customerInformationDtos.get(0).getCustomer_code());
                LambdaQueryWrapper<EnterpriseBasicInfo> updateBasic = new LambdaQueryWrapper<>();
                updateBasic.eq(EnterpriseBasicInfo::getUserId,obj.getUserId());
                this.baseMapper.update(obj,updateBasic);
            }
        });
//        enterpriseBasicInfos.forEach(obj -> {
//            body.put("customerName", obj.getCompanyName());
//            MasterDataSystemDto masterDataSystemDto =
//                    commGetFactorVerificationDto(headMap, body, url, HostConstants.HTTP_METHOD_GET, SystemConstant.MASTER_DATA_SYSTEM_TYPE_CUSTOMER);
//            if (masterDataSystemDto.getCustomerInformationDtos() != null && masterDataSystemDto.getCustomerInformationDtos().size() > 0) {
//                obj.setMasterDataSystemId(masterDataSystemDto.getCustomerInformationDtos().get(0).getId());
//            }
//            this.baseMapper.updateById(obj);
//        });
//原逻辑        
//        QueryWrapper<UserBaseInformation> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_type", SystemConstant.USER_TYPE_0);
//        queryWrapper.isNull("master_data_system_id");
//        List<UserBaseInformation> userBaseInformations = this.baseMapper.selectList(queryWrapper);
//        userBaseInformations.forEach(obj -> {
//            body.put("customerName", obj.getUserName());
//            MasterDataSystemDto masterDataSystemDto =
//                    commGetFactorVerificationDto(headMap, body, url, HostConstants.HTTP_METHOD_GET, SystemConstant.MASTER_DATA_SYSTEM_TYPE_CUSTOMER);
//            if (masterDataSystemDto.getCustomerInformationDtos() != null && masterDataSystemDto.getCustomerInformationDtos().size() > 0) {
//                obj.setMasterDataSystemId(masterDataSystemDto.getCustomerInformationDtos().get(0).getId());
//            }
//            this.baseMapper.updateById(obj);
//        });
    }

//    public MasterDataSystemDto getSupplierInformation(SupplierInformationReq requestObject) {
//        MasterDataSystemDto MasterDataSystemDto = null;
//        String url = masterDataSystemConfig.getApiHost() + masterDataSystemConfig.getUrlCustomer();
//        Map<String, Object> bodyTemp = (Map<String, Object>) CommUtils.objectToMap(requestObject);
//        Map<String, String> body = new HashMap<>();
//        bodyTemp.forEach((key, value) -> {
//            if (value != null) {
//                body.put(key, value.toString());
//            }
//        });
//        body.put("key", masterDataSystemConfig.getKey());
//        MasterDataSystemDto = commGetFactorVerificationDto(null, body, url, HostConstants.HTTP_METHOD_GET, SystemConstant.MASTER_DATA_SYSTEM_TYPE_SUPPLIER);
//        return MasterDataSystemDto;
//    }
}
